package com.ffggffgfv.backend.controller;

import com.ffggffgfv.backend.dto.AlipayRequestDTO;
import com.ffggffgfv.backend.dto.OrderCreateDTO;
import com.ffggffgfv.backend.dto.OrderDetailDTO;
import com.ffggffgfv.backend.dto.OrderQueryDTO;
import com.ffggffgfv.backend.dto.PageResult;
import com.ffggffgfv.backend.dto.PaymentDTO;
import com.ffggffgfv.backend.entity.Order;
import com.ffggffgfv.backend.service.OrderService;
import com.ffggffgfv.backend.util.JWTUtil;
import com.ffggffgfv.backend.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

/**
 * 订单控制器
 */
@RestController
@RequestMapping("/api/orders")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private JWTUtil jwtUtil;

    /**
     * 创建订单
     *
     * @param orderCreateDTO 订单创建信息
     * @param token JWT令牌
     * @return 创建结果
     */
    @PostMapping("/create")
    public Result createOrder(@RequestBody OrderCreateDTO orderCreateDTO, @RequestHeader(value = "Authorization") String token) {
        // 从令牌中获取用户ID
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未登录或登录已过期");
        }

        // 参数验证
        if (orderCreateDTO.getShippingId() == null) {
            return Result.validateFailed("收货地址不能为空");
        }

        try {
            String orderNo = orderService.createOrder(userId, orderCreateDTO);
            return Result.success(orderNo, "创建订单成功");
        } catch (Exception e) {
            return Result.validateFailed("创建订单失败: " + e.getMessage());
        }
    }    @PostMapping("/createNow")
    public Result createOrderNow (@RequestBody OrderCreateDTO orderCreateDTO, @RequestHeader(value = "Authorization") String token) {
        // 从令牌中获取用户ID
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未登录或登录已过期");
        }

        try {
            // 设置为立即购买模式
            orderCreateDTO.setBuyNow(true);
            String orderNo = orderService.createOrder(userId, orderCreateDTO);
            return Result.success(orderNo, "创建订单成功");
        } catch (Exception e) {
            return Result.validateFailed("创建订单失败: " + e.getMessage());
        }
    }

    /**
     * 获取订单详情
     *
     * @param orderNo 订单号
     * @param token JWT令牌
     * @return 订单详情
     */
    @GetMapping("/detail/{orderNo}")
    public Result getOrderDetail(@PathVariable String orderNo, @RequestHeader(value = "Authorization") String token) {
        // 从令牌中获取用户ID
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未登录或登录已过期");
        }

        OrderDetailDTO orderDetail = orderService.getOrderDetail(userId, orderNo);
        if (orderDetail == null) {
            return Result.validateFailed("订单不存在或无权访问");
        }

        return Result.success(orderDetail, "获取订单详情成功");
    }

    /**
     * 获取用户订单列表
     *
     * @param pageNum 页码
     * @param pageSize 每页数量
     * @param token JWT令牌
     * @return 订单列表
     */
    @GetMapping("/list")
    public Result getUserOrders(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestHeader(value = "Authorization") String token) {

        // 从令牌中获取用户ID
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未登录或登录已过期");
        }

        PageResult<Order> pageResult = orderService.getUserOrders(userId, pageNum, pageSize);
        return Result.success(pageResult, "获取订单列表成功");
    }

    /**
     * 取消订单
     *
     * @param orderNo 订单号
     * @param token JWT令牌
     * @return 取消结果
     */
    @PostMapping("/cancel/{orderNo}")
    public Result cancelOrder(@PathVariable String orderNo, @RequestHeader(value = "Authorization") String token) {
        // 从令牌中获取用户ID
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未登录或登录已过期");
        }

        boolean result = orderService.cancelOrder(userId, orderNo);
        if (result) {
            return Result.success(null, "取消订单成功");
        } else {
            return Result.validateFailed("取消订单失败，订单可能已支付或不存在");
        }
    }    /**
     * 支付订单
     *
     * @param paymentDTO 支付信息
     * @param token JWT令牌
     * @return 支付结果
     */
    @PostMapping("/pay")
    public Result payOrder(@RequestBody PaymentDTO paymentDTO, @RequestHeader(value = "Authorization") String token) {
        // 从令牌中获取用户ID
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未登录或登录已过期");
        }

        // 参数验证
        if (paymentDTO.getOrderNo() == null || paymentDTO.getOrderNo().trim().isEmpty()) {
            return Result.validateFailed("订单号不能为空");
        }
        if (paymentDTO.getPaymentType() == null || paymentDTO.getPaymentType() < 1 || paymentDTO.getPaymentType() > 3) {
            return Result.validateFailed("支付方式不正确");
        }

        try {
            // 获取订单信息
            Order order = orderService.getOrderByOrderNo(paymentDTO.getOrderNo());
            if (order == null) {
                return Result.validateFailed("订单不存在");
            }
            
            // 检查订单是否属于当前用户
            if (!order.getUserId().equals(userId)) {
                return Result.validateFailed("无权访问此订单");
            }
            
            // 检查订单状态
            if (order.getStatus() != 0) {
                return Result.validateFailed("订单状态不正确，无法支付");
            }

            // 根据支付方式处理
            if (paymentDTO.getPaymentType() == 2) { // 支付宝支付
                // 构建支付宝支付请求
                AlipayRequestDTO alipayRequest = new AlipayRequestDTO();
                alipayRequest.setOrderNo(paymentDTO.getOrderNo());
                alipayRequest.setTotalAmount(order.getTotalAmount().toString());
                alipayRequest.setSubject("商品订单-" + paymentDTO.getOrderNo());
                alipayRequest.setBody("购买商品");

                // 调用支付宝支付接口
                RestTemplate restTemplate = new RestTemplate();
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                headers.set("Authorization", token);
                
                HttpEntity<AlipayRequestDTO> request = new HttpEntity<>(alipayRequest, headers);
                
                try {
                    ResponseEntity<Result> response = restTemplate.postForEntity(
                        "http://localhost:8080/api/alipay/pay", 
                        request, 
                        Result.class
                    );
                    
                    return response.getBody();
                } catch (Exception e) {
                    return Result.failed("调用支付宝支付失败：" + e.getMessage());
                }
            } else {
                // 其他支付方式
                boolean result = orderService.payOrder(userId, paymentDTO);
                if (result) {
                    return Result.success(null, "支付成功");
                } else {
                    return Result.validateFailed("支付失败，订单可能已支付或已取消");
                }
            }
        } catch (Exception e) {
            return Result.failed("支付处理异常：" + e.getMessage());
        }
    }

    /**
     * 确认收货
     *
     * @param orderNo 订单号
     * @param token JWT令牌
     * @return 确认结果
     */
    @PostMapping("/confirm/{orderNo}")
    public Result confirmReceipt(@PathVariable String orderNo, @RequestHeader(value = "Authorization") String token) {
        // 从令牌中获取用户ID
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未登录或登录已过期");
        }

        boolean result = orderService.confirmReceipt(userId, orderNo);
        if (result) {
            return Result.success(null, "确认收货成功");
        } else {
            return Result.validateFailed("确认收货失败，订单可能未发货或不存在");
        }
    }

    /**
     * 管理员专用：按条件查询订单
     *
     * @param status 订单状态
     * @param orderNo 订单号
     * @param pageNum 页码
     * @param pageSize 每页数量
     * @param token JWT令牌
     * @return 订单列表
     */
    @GetMapping("/admin/list")
    public Result adminListOrders(
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String orderNo,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestHeader(value = "Authorization") String token) {

        // 权限校验（这里简化处理，实际应当检查是否为管理员）
        if (token == null || !token.startsWith("Bearer ")) {
            return Result.unauthorized("无效的认证令牌");
        }

        OrderQueryDTO queryDTO = new OrderQueryDTO();
        queryDTO.setStatus(status);
        queryDTO.setOrderNo(orderNo);
        queryDTO.setPageNum(pageNum);
        queryDTO.setPageSize(pageSize);

        PageResult<Order> pageResult = orderService.getOrdersByCondition(queryDTO);
        return Result.success(pageResult, "获取订单列表成功");
    }

    /**
     * 管理员专用：订单发货
     *
     * @param orderNo 订单号
     * @param trackingNo 物流单号
     * @param shippingCompany 物流公司
     * @param token JWT令牌
     * @return 发货结果
     */
    @PostMapping("/admin/ship")
    public Result shipOrder(
            @RequestParam String orderNo,
            @RequestParam String trackingNo,
            @RequestParam String shippingCompany,
            @RequestHeader(value = "Authorization") String token) {

        // 权限校验（这里简化处理，实际应当检查是否为管理员）
        if (token == null || !token.startsWith("Bearer ")) {
            return Result.unauthorized("无效的认证令牌");
        }

        // 参数验证
        if (orderNo == null || orderNo.trim().isEmpty()) {
            return Result.validateFailed("订单号不能为空");
        }
        if (trackingNo == null || trackingNo.trim().isEmpty()) {
            return Result.validateFailed("物流单号不能为空");
        }
        if (shippingCompany == null || shippingCompany.trim().isEmpty()) {
            return Result.validateFailed("物流公司不能为空");
        }

        boolean result = orderService.shipOrder(orderNo, trackingNo, shippingCompany);
        if (result) {
            return Result.success(null, "订单发货成功");
        } else {
            return Result.validateFailed("订单发货失败，订单可能未支付或不存在");
        }
    }

    /**
     * 从令牌中提取用户ID
     *
     * @param token JWT令牌
     * @return 用户ID
     */
    private Long getUserIdFromToken(String token) {
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            try {
                return jwtUtil.getUserIdFromToken(token);
            } catch (Exception e) {
                return null;
            }
        }
        return null;
    }
}
